<template>
  <el-card>
    <template #header>
      <h2>外出申请管理</h2>
    </template>

    <!-- 搜索栏 -->
    <el-form inline class="toolbar">
      <el-form-item label="客户姓名">
        <el-input v-model="filters.name" placeholder="模糊搜索" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 外出申请列表 -->
    <el-table
      :data="applications"
      stripe
      style="margin-top: 16px; width: 100%"
    >
      <el-table-column type="index" label="序号" width="60" />

      <el-table-column prop="customerName" label="客户名称" />
      <el-table-column prop="reason" label="外出事由" />
      <el-table-column prop="outTime" label="外出时间" />
      <el-table-column prop="expectedReturn" label="预计返回时间" />
      <el-table-column prop="actualReturn" label="实际返回时间" />
      <el-table-column prop="companionName" label="陪同人" />
      <el-table-column prop="companionRelation" label="关系" />
      <el-table-column prop="companionPhone" label="陪同人电话" />

      <!-- 审批状态 -->
      <el-table-column label="审批状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.approveStatus)" effect="dark">
            {{ getStatusLabel(row.approveStatus) }}
          </el-tag>
        </template>
      </el-table-column>
	  <!-- 审批人 -->
	  <el-table-column prop="operatorUserName" label="审批人" width="120" />
	  <el-table-column prop="approveTime" label="审批时间" :formatter="formatDate" width="140" />


      <!-- 操作列 -->
      <el-table-column label="操作" width="180">
        <template #default="{ row }">
          <el-button
            v-if="row.approveStatus === 0"
            type="danger"
            size="small"
            @click="revoke(row)"
          >
            撤销申请
          </el-button>
          <el-button
            v-else-if="row.approveStatus === 1"
            type="primary"
            size="small"
            @click="registerReturn(row)"
          >
            登记回院时间
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      style="margin-top: 20px; text-align: right;"
      :current-page="currentPage"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 50]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @current-change="onPageChange"
      @size-change="onSizeChange"
    />
  </el-card>
</template>

<script setup>
import { ref, reactive, onMounted, inject } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'
import qs from 'qs'
import { jwtDecode } from 'jwt-decode'

const axios = inject('axios')

// 搜索条件
const filters = reactive({ name: '' })
// 列表数据
const applications = ref([])
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 健康管家ID
const nurseId = ref(null)
  const init = ()=>{
      let token=sessionStorage.getItem('token');
      const payload = jwtDecode(token);
      const user = JSON.parse(payload.mobileJson)
      nurseId.value=user.id;
      console.log(nurseId.value);
  }
  init();

  const getStatusLabel = (status) => {
    switch (status) {
      case 0: return '待审批';
      case 1: return '已通过';
      case 2: return '已拒绝';
      default: return '未知';
    }
  };
  
  const getStatusType = (status) => {
    switch (status) {
      case 0: return 'warning'; // 黄色
      case 1: return 'success'; // 绿色
      case 2: return 'danger';  // 红色
      default: return 'info';   // 灰蓝色
    }
  };
  
  // 精确到秒
  const formatDateTime = (row, col, val) => val ? dayjs(val).format('YYYY-MM-DD HH:mm:ss') : '';

// 拉申请列表
async function fetchApplications() {
  const { data: rb } = await axios.post(
    'OutRegistrationController/search',
    qs.stringify({
      healthManagerId: nurseId.value,
      clientName: filters.name,
      cur: currentPage.value,
      number: pageSize.value
    })
  )
  if (rb.status === 200) {
    applications.value = rb.data
    total.value = rb.total
  } else {
    ElMessage.error('加载失败：' + rb.message)
  }
}

// 点击“查询”按钮
function onSearch() {
  currentPage.value = 1
  fetchApplications()
}

// 分页回调
function onPageChange(page) {
  currentPage.value = page
  fetchApplications()
}
function onSizeChange(size) {
  pageSize.value = size
  currentPage.value = 1
  fetchApplications()
}

// 撤销
async function revoke(row) {
  await ElMessageBox.confirm('确认撤销该申请？', '提示', { type: 'warning' })
  const { data: rb } = await axios.post(
    'OutRegistrationController/revoke',
    qs.stringify({
      id: row.id,
    })
  )
  if (rb.status === 200) {
    ElMessage.success('已撤销')
    fetchApplications()
  } else {
    ElMessage.error('撤销失败：' + rb.message)
  }
}

// 登记回院
async function registerReturn(row) {
  const res = await ElMessageBox.prompt('请输入回院时间', '登记回院时间', {
    inputType: 'datetime-local',
    confirmButtonText: '提交',
    cancelButtonText: '取消'
  })
  if (!res.value) return
  const actual = dayjs(res.value).format('YYYY-MM-DD HH:mm:ss')
  const { data: rb } = await axios.post(
    'OutRegistrationController/registerReturn',
    qs.stringify({
      id: row.id,
      actualReturnTime: actual
    })
  )
  if (rb.status === 200) {
    ElMessage.success('登记成功')
    fetchApplications()
  } else {
    ElMessage.error('登记失败：' + rb.message)
  }
}

fetchApplications()
</script>

<style scoped>
.toolbar {
  margin-bottom: 16px;
}
</style>
